<?php
/**
 * Used to input filters into a report
 *
 * @author Iain Edminster
 */
class Bliss_DataReport_Filter
{
	/**
	 * Table field to filter
	 * @var string
	 */
	protected $_field;

	/**
	 * Holds the filter's label
	 * @var string
	 */
	protected $_label;

	/**
	 * Holds the filter's parameters
	 * @var Zend_Config
	 */
	protected $_params;

	/**
	 * Stores the filter's value
	 * @var <type>
	 */
	protected $_value;

	/**
	 * Class constructor
	 * Sets the parameters for the filter
	 *
	 * @param string $field
	 * @param string $label
	 * @param array $params
	 */
	public function __construct($field, $label=null, $params=array())
	{
		$this->_field	= $field;
		$this->_label	= $label;
		$this->_params	= new Zend_Config($params, true);
	}

	/**
	 * Returns the condition for the DB select where statement
	 * @return string
	 */
	public function getCondition()
	{
		$compare	= isset($this->_params->compare) ? $this->_params->compare : '=';
		return "{$this->_field} {$compare} ?";
	}

	/**
	 * Sets the value to use in the DB select statement
	 * 
	 * @param string $value
	 */
	public function setValue($value)
	{
		$this->_value = $value;
	}

	/**
	 * Returns the formatted value for the DB select where statement
	 *
	 * @param string $value
	 * @return string
	 */
	public function getValue($value=null)
	{
		$value	= isset($value) ? $value : $this->_value;
		return $this->formatValue($value);
	}

	/**
	 * Returns the real value of the filter
	 * 
	 * @return string
	 */
	public function getRealValue()
	{
		if($this->_value instanceOf Zend_Config) {
			$value = array();
			foreach($this->_value as $k => $v) {
				$value[$k] = $v;
			}
			return $value;
		}
		
		return $this->_value;
	}

	/**
	 * Returns the passed value with proper formatting
	 *
	 * @param string $value
	 * @return string
	 */
	public function formatValue($value)
	{
		$format	= isset($this->_params->format) ? $this->_params->format : '?';
		return str_replace("?", $value, $format);
	}

	/**
	 * Sets the filter's label
	 *
	 * @param string $label
	 */
	public function setLabel($label)
	{
		$this->_label	= $label;
	}

	/**
	 * Gets the filter's label
	 * 
	 * @return string
	 */
	public function getLabel()
	{
		return $this->_label;
	}

	/**
	 * Returns the value of a parameter
	 *
	 * @return mixed
	 */
	public function __get($key)
	{
		return $this->_params->{$key};
	}

	/**
	 * Checks if a filter parameter exists.
	 *
	 * @return bool
	 */
	public function __isset($key)
	{
		return isset($this->_params->{$key});
	}
}
?>
